# -*- coding: utf-8 -*-
# @Date   : 2019/12/10
# @File   : R13_EC_EnforcementCheck_WHB_2D.py
# @Author : breeze


'''eof
name:申请企业企业征信新增强制执行记录
code:R13_EC_EnforcementCheck_WHB_2D
tableName:
columnName:
groups:弱规则>企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''
import json
import sys
import pandas as pd
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d') for i in
                  range(6)]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float):
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


# 获取 上次申请时间
def get_relative_date():
    relative_date = ratingRequest.get('relativeDate')
    return dateFormat(relative_date)


def R13_EC_EnforcementCheck_WHB_2D():
    now_date = datetime.datetime.now().strftime('%Y-%m-%d')
    relativeDate = get_relative_date()
    if relativeDate is None:
        raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
    data = EC_DSJ_2D.get('data')
    factor = []
    # 法院信息 EFB[1,1]
    EFB = getTable(data, 'EFB', 1, 0)
    if EFB == [{}]:
        return u'缺失值'
    elif EFB == 0:
        return 1
    else:
        # 强制执行记录信息单元 EF03[0,*]
        EF03 = getTable(EFB[0], 'EF03', 0, 1)
        if EF03 == [{}]:
            return u'缺失值'
        elif EF03 == 0:
            return 1
        else:
            for i in EF03:
                try:
                    # 立案日期
                    EF030R01 = dateFormat(i.get('EF030R01'))
                    # 申请执行标的金额
                    EF030J02 = i.get('EF030J01')
                    if isfloat(EF030J02) is False:
                        # 已执行标的金额
                        EF030J02 = i.get('EF030J02')
                    # 案号
                    EF030I02 = i.get('EF030I02')
                    # 限定 立案日期  在上次申请时间到本次申请时间之前
                    if EF030R01 is not None and EF030I02 not in null_type_list:
                        if EF030R01 > now_date:
                            factor.append(0)
                        elif relativeDate < EF030R01:
                            if EF030R01 < last_year_list[5]:
                                factor.append(1)
                            elif isfloat(EF030J02) is False:
                                factor.append(0)
                            elif float(EF030J02) <= 0:
                                factor.append(1)
                            elif last_year_list[2] < EF030R01 <= last_year_list[0]:
                                if 0 < float(EF030J02) < 6000:
                                    factor.append(1)
                                else:
                                    factor.append(0)
                            elif last_year_list[3] < EF030R01 <= last_year_list[2]:
                                if 0 < float(EF030J02) <= 15000:
                                    factor.append(1)
                                else:
                                    factor.append(0)
                            elif last_year_list[5] < EF030R01 <= last_year_list[3]:
                                if 0 < float(EF030J02) <= 25000:
                                    factor.append(1)
                                else:
                                    factor.append(0)
                            else:
                                factor.append(1)
                        else:
                            factor.append(1)
                    else:
                        factor.append(0)
                except:
                    continue

    if len(factor) == 0:
        return u'缺失值'
    elif 0 in factor:
        return 0
    else:
        return 1


if __name__ == '__main__':
    ratingRequest = {"relativeDate": "20191212"}
    file_obj = open(r'../data/WHB/R13_EC_EnforcementCheck_WHB/EC_DSJ_2D.json', 'r')
    content = file_obj.read()
    EC_DSJ_2D = json.loads(content, strict=False)
    aa = R13_EC_EnforcementCheck_WHB_2D()
    print aa

result = R13_EC_EnforcementCheck_WHB_2D()
